// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 获取DOM元素
    const editor = document.getElementById('editor');
    const previewContainer = document.querySelector('.preview-container');
    const platformSelect = document.getElementById('platform-selector');
    const modeToggleBtn = document.getElementById('mode-toggle-btn');
    const copyBtn = document.getElementById('copy-btn');
    const saveBtn = document.getElementById('save-btn');
    const exportBtn = document.getElementById('export-btn');
    const fullscreenEditBtn = document.getElementById('fullscreen-edit-btn');
    const wordCount = document.getElementById('word-count');
    const charCount = document.getElementById('char-count');
    
    // 工具栏按钮
    const boldBtn = document.getElementById('bold-btn');
    const italicBtn = document.getElementById('italic-btn');
    const headingBtn = document.getElementById('heading-btn');
    const linkBtn = document.getElementById('link-btn');
    const imageBtn = document.getElementById('image-btn');
    const listBtn = document.getElementById('list-btn');
    const quoteBtn = document.getElementById('quote-btn');
    const codeBtn = document.getElementById('code-btn');
    
    // 初始化Markdown解析器
    marked.setOptions({
        breaks: true,
        gfm: true,
        tables: true,
        sanitize: false
    });
    
    // 电脑/手机模式切换
    let isMobileMode = true; // 默认为手机模式
    
    // 滚动同步变量
    let isEditorScrolling = false;
    let isPreviewScrolling = false;
    
    // 防抖函数
    function debounce(func, wait) {
        let timeout;
        return function(...args) {
            clearTimeout(timeout);
            timeout = setTimeout(() => func.apply(this, args), wait);
        };
    }

    // 实时更新预览内容（带防抖）
    const updatePreview = debounce(() => {
        const content = editor.value;
        const preview = document.getElementById('preview');
        
        if (preview) {
            const markdownText = editor.value;
            const html = marked.parse(markdownText);
            preview.innerHTML = html;
            
            // 应用当前选择的平台样式
            applyPlatformStyle();
            
            // 高亮代码块
            document.querySelectorAll('pre code').forEach((block) => {
                hljs.highlightElement(block);
            });
            
            // 更新字数统计
            updateWordCount();
        }
    }, 200);
    
    // 应用平台特定样式
    function applyPlatformStyle() {
        const platform = platformSelect.value;
        const preview = document.getElementById('preview');
        if (preview) {
            preview.classList.remove('wechat', 'zhihu', 'toutiao', 'xiaohongshu');
            if (platform !== 'default') {
                preview.classList.add(platform);
            }
        }
    }
    
    // 更新字数统计
    function updateWordCount() {
        const text = editor.value;
        const charNum = text.length;
        const wordNum = text.trim() === '' ? 0 : text.trim().split(/\s+/).length;
        
        wordCount.textContent = `字数: ${wordNum}`;
        charCount.textContent = `字符: ${charNum}`;
    }
    
    // 处理编辑器滚动
    function handleEditorScroll() {
        if (!isPreviewScrolling) {
            isEditorScrolling = true;
            const preview = document.getElementById('preview');
            if (preview) {
                const editorScrollRatio = editor.scrollTop / (editor.scrollHeight - editor.clientHeight);
                const previewScrollTarget = editorScrollRatio * (preview.scrollHeight - preview.clientHeight);
                preview.scrollTop = previewScrollTarget;
            }
            setTimeout(() => {
                isEditorScrolling = false;
            }, 50);
        }
    }
    
    // 处理预览区滚动
    function handlePreviewScroll() {
        if (!isEditorScrolling) {
            isPreviewScrolling = true;
            const preview = document.getElementById('preview');
            if (preview) {
                const previewScrollRatio = preview.scrollTop / (preview.scrollHeight - preview.clientHeight);
                const editorScrollTarget = previewScrollRatio * (editor.scrollHeight - editor.clientHeight);
                editor.scrollTop = editorScrollTarget;
            }
            setTimeout(() => {
                isPreviewScrolling = false;
            }, 50);
        }
    }
    
    // 手机预览模式
    function switchToMobileMode() {
        // 清除之前的内容
        previewContainer.innerHTML = '';
        
        // 创建手机预览结构
        const previewHeader = document.createElement('div');
        previewHeader.className = 'preview-header';
        previewHeader.innerHTML = `
            <div class="title-section">
                <span>手机预览</span>
            </div>
            <div class="preview-controls">
                <select id="platform-selector" class="styled-select">
                    <option value="default">默认样式</option>
                    <option value="wechat">微信公众号</option>
                    <option value="toutiao">今日头条</option>
                    <option value="zhihu">知乎</option>
                    <option value="xiaohongshu">小红书</option>
                </select>
                <button id="mode-toggle-btn" class="primary-btn"><i class="fa fa-desktop"></i> 电脑预览</button>
                <button id="copy-btn" class="primary-btn"><i class="fa fa-copy"></i> 复制预览</button>
                <button id="fullscreen-preview-btn" class="icon-btn" title="全屏预览"><i class="fa fa-expand"></i></button>
            </div>
        `;
        
        const phoneFrame = document.createElement('div');
        phoneFrame.className = 'phone-frame';
        
        const phoneDevice = document.createElement('div');
        phoneDevice.className = 'phone-device';
        
        const phoneNotch = document.createElement('div');
        phoneNotch.className = 'phone-notch';
        
        const phoneScreen = document.createElement('div');
        phoneScreen.className = 'phone-screen';
        
        const phoneStatusBar = document.createElement('div');
        phoneStatusBar.className = 'phone-status-bar';
        phoneStatusBar.innerHTML = `
            <div class="phone-time" id="phone-time">12:30</div>
            <div class="phone-icons">
                <i class="fa fa-signal"></i>
                <i class="fa fa-wifi"></i>
                <i class="fa fa-battery-full"></i>
            </div>
        `;
        
        const phoneContent = document.createElement('div');
        phoneContent.className = 'phone-content';
        
        const preview = document.createElement('div');
        preview.id = 'preview';
        preview.className = 'preview mobile';
        
        const phoneHomeIndicator = document.createElement('div');
        phoneHomeIndicator.className = 'phone-home-indicator';
        
        // 组装DOM结构
        phoneContent.appendChild(preview);
        phoneScreen.appendChild(phoneStatusBar);
        phoneScreen.appendChild(phoneContent);
        phoneScreen.appendChild(phoneHomeIndicator);
        phoneDevice.appendChild(phoneNotch);
        phoneDevice.appendChild(phoneScreen);
        phoneFrame.appendChild(phoneDevice);
        
        previewContainer.appendChild(previewHeader);
        previewContainer.appendChild(phoneFrame);
        
        // 重新绑定事件
        rebindEvents();
        
        // 更新预览内容
        updatePreview();
        
        // 添加滚动事件监听
        preview.addEventListener('scroll', handlePreviewScroll);
    }
    
    // 电脑预览模式
    function switchToDesktopMode() {
        // 清除之前的内容
        previewContainer.innerHTML = '';
        
        // 创建电脑预览结构
        const previewHeader = document.createElement('div');
        previewHeader.className = 'preview-header';
        previewHeader.innerHTML = `
            <div class="title-section">
                <span>预览区</span>
            </div>
            <div class="preview-controls">
                <select id="platform-selector" class="styled-select">
                    <option value="default">默认样式</option>
                    <option value="wechat">微信公众号</option>
                    <option value="toutiao">今日头条</option>
                    <option value="zhihu">知乎</option>
                    <option value="xiaohongshu">小红书</option>
                </select>
                <button id="mode-toggle-btn" class="primary-btn"><i class="fa fa-mobile"></i> 手机预览</button>
                <button id="copy-btn" class="primary-btn"><i class="fa fa-copy"></i> 复制预览</button>
                <button id="fullscreen-preview-btn" class="icon-btn" title="全屏预览"><i class="fa fa-expand"></i></button>
            </div>
        `;
        
        const preview = document.createElement('div');
        preview.id = 'preview';
        preview.className = 'preview';
        
        previewContainer.appendChild(previewHeader);
        previewContainer.appendChild(preview);
        
        // 重新绑定事件
        rebindEvents();
        
        // 更新预览内容
        updatePreview();
        
        // 添加滚动事件监听
        preview.addEventListener('scroll', handlePreviewScroll);
    }
    
    // 重新绑定事件
    function rebindEvents() {
        const newPlatformSelect = document.getElementById('platform-selector');
        const newModeToggleBtn = document.getElementById('mode-toggle-btn');
        const newCopyBtn = document.getElementById('copy-btn');
        const newFullscreenPreviewBtn = document.getElementById('fullscreen-preview-btn');
        
        newPlatformSelect.addEventListener('change', () => {
            applyPlatformStyle();
            updatePreview();
        });
        
        newModeToggleBtn.addEventListener('click', () => {
            isMobileMode = !isMobileMode;
            if (isMobileMode) {
                switchToMobileMode();
            } else {
                switchToDesktopMode();
            }
        });
        
        newCopyBtn.addEventListener('click', () => {
            const preview = document.getElementById('preview');
            if (preview) {
                // 创建一个临时容器来处理富文本
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = preview.innerHTML;
                
                // 处理代码块的格式
                tempDiv.querySelectorAll('pre code').forEach(block => {
                    block.style.fontFamily = 'Consolas, monospace';
                    block.style.fontSize = '14px';
                    block.style.padding = '1em';
                    block.style.display = 'block';
                    // 移除背景色
                });
                
                // 处理图片
                tempDiv.querySelectorAll('img').forEach(img => {
                    img.style.maxWidth = '100%';
                    img.style.height = 'auto';
                });
                
                // 处理引用块
                tempDiv.querySelectorAll('blockquote').forEach(quote => {
                    quote.style.borderLeft = '4px solid #07C160';
                    quote.style.padding = '0.5em 1em';
                    quote.style.margin = '1em 0';
                    quote.style.color = '#666';
                    // 移除背景色
                });
                
                // 处理标题
                ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].forEach(tag => {
                    tempDiv.querySelectorAll(tag).forEach(heading => {
                        heading.style.fontWeight = 'bold';
                        heading.style.color = '#07C160';
                    });
                });
                
                // 处理链接
                tempDiv.querySelectorAll('a').forEach(link => {
                    link.style.color = '#07C160';
                    link.style.textDecoration = 'none';
                });
                
                // 处理列表
                tempDiv.querySelectorAll('ul, ol').forEach(list => {
                    list.style.paddingLeft = '2em';
                    list.style.margin = '1em 0';
                });
                
                // 创建一个临时的可编辑div用于复制
                const tempEditable = document.createElement('div');
                tempEditable.contentEditable = true;
                tempEditable.innerHTML = tempDiv.innerHTML;
                document.body.appendChild(tempEditable);
                
                // 选择内容
                const range = document.createRange();
                range.selectNodeContents(tempEditable);
                const selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
                
                // 执行复制
                try {
                    document.execCommand('copy');
                    showToast('富文本内容已复制，可直接粘贴到公众号');
                } catch (err) {
                    showToast('复制失败，请重试');
                }
                
                // 清理
                document.body.removeChild(tempEditable);
                selection.removeAllRanges();
            }
        });
        
        newFullscreenPreviewBtn.addEventListener('click', toggleFullscreenPreview);
    }
    
    // 显示提示消息
    function showToast(message) {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.classList.add('show');
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
    
    // 切换全屏预览
    function toggleFullscreenPreview() {
        const preview = document.getElementById('preview');
        if (!document.fullscreenElement) {
            preview.requestFullscreen();
        } else {
            document.exitFullscreen();
        }
    }
    
    // 初始化为手机预览模式
    switchToMobileMode();
    
    // 绑定编辑器事件
    editor.addEventListener('input', updatePreview);
    editor.addEventListener('scroll', handleEditorScroll);
    
    // 绑定工具栏按钮事件
    boldBtn.addEventListener('click', () => insertText('**', '**', '粗体文本'));
    italicBtn.addEventListener('click', () => insertText('*', '*', '斜体文本'));
    headingBtn.addEventListener('click', () => insertText('## ', '', '标题'));
    linkBtn.addEventListener('click', () => insertText('[', '](链接地址)', '链接文本'));
    imageBtn.addEventListener('click', () => insertText('![', '](图片地址)', '图片描述'));
    listBtn.addEventListener('click', () => insertText('- ', '', '列表项'));
    quoteBtn.addEventListener('click', () => insertText('> ', '', '引用文本'));
    codeBtn.addEventListener('click', () => insertText('```\n', '\n```', '代码块'));
    
    // 获取编辑器当前选择内容
    function getEditorSelection() {
        const start = editor.selectionStart;
        const end = editor.selectionEnd;
        return {
            start,
            end,
            text: editor.value,
            selection: editor.value.substring(start, end)
        };
    }

    // 设置编辑器内容和光标位置
    function setEditorContent(content, cursorPos) {
        editor.value = content;
        editor.focus();
        editor.setSelectionRange(cursorPos, cursorPos);
        updatePreview();
    }

    // 插入文本函数
    function insertText(before, after, placeholder) {
        const { start, end, text, selection } = getEditorSelection();
        
        const newText = selection ? before + selection + after : before + placeholder + after;
        const newContent = text.substring(0, start) + newText + text.substring(end);
        const newCursorPos = selection ? start + before.length + selection.length + after.length : start + before.length + placeholder.length;
        
        setEditorContent(newContent, newCursorPos);
    }
});